import { useState, useRef } from 'react'
import './App.css'

function ControlledInput({ onSubmit }) {
  const [value, setValue] = useState('') // 响应式状态
  const [error, setError] = useState('')
  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(value)
    onSubmit(value)
  }
  const handleChange = (e) => {
    setValue(e.target.value)
    // 频繁触发 实时判断表单是否合格
    if (e.target.value.length < 3) {
      setError('请输入至少 3 个字符')
    } else {
      setError('')
    }
  }
  return (
   <form onSubmit={handleSubmit}>
    <label htmlFor="controll-input">受控组件</label>
    <input
      id="controll-input"
      type="text"
      value={value}
      onChange={handleChange}
      required
    />
    {error && <div>{error}</div>}
    <button type="submit">提交</button>
   </form>
  )
}

function UncontrolledInput({ onSubmit }) {
  const inputRef = useRef(null)
  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(inputRef.current.value)
    onSubmit(inputRef.current.value)
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="uncontroll-input">非受控组件</label>
      <input
        id="uncontroll-input"
        type="text"
        ref={inputRef}
      />
      <button type="submit">提交</button>
    </form>
  )
}

function App() {
  const handleSubmit = (value) => {
    console.log(value)
  }

  return (
    <>
      <ControlledInput onSubmit={handleSubmit} />
      <UncontrolledInput onSubmit={handleSubmit} />
    </>
  )
}

export default App
